import { fileURLToPath, URL } from "node:url";
import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'
import react from '@vitejs/plugin-react'
import viteCompression from "vite-plugin-compression"

// https://vitejs.dev/config/
export default defineConfig((mdoe: ConfigEnv): UserConfig => {
  const env = loadEnv(mdoe.mode, process.cwd())
  const viteEnv = warppEnv(env)
  console.log(viteEnv)
  return {
    plugins: [
      react(),
      // gzip
      viteEnv.VITE_USE_COMPRESS && viteCompression({
        gzipExtensions: ['js', 'css', 'html', 'svg'],
        threshold: 10240,
        minRatio: 0.8,
        brotliOptions: {
          mode: 'text',
          quality: 11,
        },
      })
    ],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),

      }
    },
    server: {
      host: '0.0.0.0',
      port: viteEnv.VITE_PORT,
      open: viteEnv.VITE_OPEN,
      proxy: {
        '/api': {
          target: viteEnv.VITE_API_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      // esbuild打包更快，但是不能去除console日志，使用tarser可以去除
      outDir: 'dist',
      minify: viteEnv.VITE_USE_CONSOLE ? 'esbuild' : 'terser',
      target: 'es2015',
      rollupOptions: {
        output: {
          // 打包后输出的文件名
          entryFileNames: 'static/js/[name].[hash].js',
          chunkFileNames: 'assets/js/[name].[hash].js',
          assetFileNames: 'static/[extname]/[name].[hash][extname]',
        },
      }
    }
  }
})

// 加载env的方法
function warppEnv(envConf: { [x: string]: string; }) {
  const ret: any = {};
  for (const envName of Object.keys(envConf)) {
    let realName: any = envConf[envName].replace(/\\n/g, '\n');
    realName = realName === 'true' ? true : realName === 'false' ? false : realName
    if (envName === 'VITE_PORT') {
      realName = Number(realName)
    }
    if (envName === 'VITE_PROXY') {
      try {
        realName = JSON.parse(realName)
      } catch (err) {
        console.error(`Parse VITE_PROXY error: ${err.message}`);
      };
    }
    ret[envName] = realName;
    process.env[envName] = realName;
  }
  return ret;
}